RM.Pages.Functions.livechat_admin_isTyping = {}; // used to track if admin is typing a message

// these panels are just used for generating an event to trigger the new message
RM.Pages.LiveChat_NotifyNewMessageSoundPanel = {
    xtype: "panel",
    width: 100,
    height: 40,
    title: "",
    html: "loading...",
    id : "rm_pages_modules_livechat_sound_newmessagealert_panel",
    plugins:[
        new Ext.ux.Media.plugin.AudioEvents({
              audioEvents :{
                 beforehide : RM.RootURL+'RM/userdata/modules/LiveChat/images/bong.wav'
              },
              volume : 0.7
        })
    ]
};

// this panel is just used for generating an event to trigger the new chat request sound
RM.Pages.LiveChat_NotifyNewChatRequestSoundPanel = {
    xtype: "panel",
    width: 100,
    height: 40,
    title: "",
    html: "loading...",
    id : "rm_pages_modules_livechat_sound_newchatrequest_panel",
    plugins:[
        new Ext.ux.Media.plugin.AudioEvents({
              audioEvents :{
                 beforehide : RM.RootURL+'RM/userdata/modules/LiveChat/images/ring.wav'
              },
              volume : 1
        })
    ]
};


/**
 * store for new chat requests, used on the left panel
 * RM.Pages.LiveChat_List_Grid created later in this process
 */
RM.Pages.LiveChat_List_Json_Store = new Ext.data.JsonStore({
    url: RM.Common.AssembleURL({
        controller: 'LiveChat',
        action: 'listchattersJson'
    }),
    id: 'rm_livechat_list_grid_json_store',
    totalProperty: 'total',
    root: 'data',
    fields: [
        {name: "id"},
        {name: "user_name"},
        {name: "user_email"},
        {name: "question"}

    ],
    sortInfo: {field: 'id', direction: 'DESC'},
    remoteSort: true
});

/**
 * used by the RM.Pages.LiveChat_List_Grid created later in this process
 */
RM.Pages.LiveChat_List_Columns_Rows = [
    {dataIndex: 'id', header: RM.Translate.Common.Id,renderer: function(id){return '<a href="javascript:RM.Pages.Functions.livechat_accept_chat(\''+id+'\')">'+id+'</a>';}},
    {dataIndex: 'user_name', header: RM.Translate.Common.Name},
    {dataIndex: 'user_email', header: RM.Translate.Common.Email},
    {dataIndex: 'question', header: RM.Translate.Admin.LiveChat.List.Question}
];
/**
 * used by the RM.Pages.LiveChat_List_Grid created later in this process
 */
RM.Pages.LiveChat_List_Columns = new Ext.grid.ColumnModel(RM.Pages.LiveChat_List_Columns_Rows);


/**
 * expand and update the Livechat menu item
 */
RM.Pages.Functions.livechat_ExpandandMarkMenu = function(){

    // if the form is not visable:-
    // expand the menu and add a * to the menu item
    if (!Ext.getCmp("rm_main_tree_menu").root.findChild("id", "Modules_InfoJson").findChild("id","LiveChat_EditJson").isSelected()){
        try{
            // add * to the menu
            Ext.getCmp("rm_main_tree_menu").root.findChild("id", "Modules_InfoJson").findChild("id","LiveChat_EditJson").setText("<b>"+RM.Translate.Admin.LiveChat.Main.name+"</b>");
            // if we get a message expand the menu to the livechat node
            Ext.getCmp("rm_main_tree_menu").expandPath(RM.Pages.Function.LiveChat_MenuNodePath);
        } catch (err1){
            // unsed
        }
    } else {
        // if it's visable the make sure the menu name is correct.
        try{
            Ext.getCmp("rm_main_tree_menu").root.findChild("id", "Modules_InfoJson").findChild("id","LiveChat_EditJson").setText(RM.Translate.Admin.LiveChat.Main.name);
        } catch (err2){
            // unsed
        }
    }
};

/**
 * this is the main method used by the chat dialogue update it is used to
 * add the items to the chat window.
 *
 * note: we have to use eval as the id's are created from a combination of the
 * string+chat id
 */
RM.Pages.Functions.livechat_ListViewAddRow = function(data, chat_id){

    if (data.user===undefined && data.operator===undefined){
        return;
    }

    // get the store and assign to a local variable
    eval("var storeVar = RM.Pages.LiveChat_DialogueStore_"+chat_id);
    var store = Ext.getCmp(storeVar);

    // get the grid and assign to a local variable
    eval('var gridVar = "rm_pages_modules_livechat_dialogue_listview_'+chat_id+'"');
    var grid = Ext.getCmp(gridVar);

    var rowData = new grid.store.recordType({
            id: data.id,
            operator: data.operator,
            user: data.user
    });

    // trigger the sound for the new message
    Ext.getCmp("rm_pages_modules_livechat_sound_newmessagealert_panel").show();
    Ext.getCmp("rm_pages_modules_livechat_sound_newmessagealert_panel").hide();

    grid.store.add(rowData);
    grid.getView().focusRow(grid.store.data.items.length-1);

    // add a read icon to the tabpanel

    var activeTab = Ext.getCmp('rm_pages_livechat_message_tabpanel').getActiveTab();

    eval('var tabpanelVar = "rm_pages_livechat_dialogue_'+chat_id+'"');
    var tabpanel = Ext.getCmp(tabpanelVar);
    if (tabpanel.id !== activeTab.id) {
        tabpanel.setIconClass("RM_generic_red_icon");
    } else {
        tabpanel.setIconClass("RM_generic_green_icon");
    }

    // update the menu status
    RM.Pages.Functions.livechat_ExpandandMarkMenu();

    eval('var messagebox = "rm_pages_modules_livechat_messagebox_'+chat_id+'"');
    Ext.getCmp(messagebox).focus();
};

/**
 * creates the ajax request to get the new chat items.
 * sends the data to RM.Pages.Functions.livechat_ListViewAddRow for adding
 * to the chat window
 */
RM.Pages.Functions.livechat_getNewChatItems = function(chat_id){

    var isTyping = 0;

    // RM.Pages.Functions.livechat_admin_isTyping contains: [1] is typing status, [0] chat_id
    if (RM.Pages.Functions.livechat_admin_isTyping.status===true && RM.Pages.Functions.livechat_admin_isTyping.ChatID === chat_id){
       isTyping = 1;
       RM.Pages.Functions.livechat_admin_isTyping.status = false; // set it to false so we cancel the is typing
    }

    var request = {
        url: RM.Common.AssembleURL({
            controller : 'LiveChat',
            action: 'dialogueJson',
            parameters : [{
                name : 'chat_id',
                value : chat_id
            },{
                name: 'isTyping',
                value: isTyping
            }]
        }),
        method: 'POST',
        success: function(responseObject) {

            var jsonObject = Ext.util.JSON.decode(responseObject.responseText);
            var message = {};

            // if the operator closes the chat the closed flag will be set if this is set we need to inform the user
            if (jsonObject.chatInfo[0].closed === "1"){
                message.operator = "";
                message.user = RM.Translate.Admin.LiveChat.Chat.UserNotAvailable;
                RM.Pages.Functions.livechat_ListViewAddRow(message, chat_id);
                return;
            }

            // is typing indicator
            if (jsonObject.isTyping !== "0"){
                Ext.getCmp("rm_livechat_chat_toolbar").setText("RM.Translate.Admin.LiveChat.Chat.UserTyping");
            } else {
                Ext.getCmp("rm_livechat_chat_toolbar").setText("");
            }

            if (jsonObject.data.length !== 0 ){

                var i = 0;for(i; i < jsonObject.data.length; i++){
                    // add each message to the window
                    message.id = jsonObject.data[i].id;
                    if (jsonObject.data[i].operator!=="") {message.operator = RM.Pages.Functions.livechat_encode.decode(jsonObject.data[i].operator);}else{message.operator ="";}
                    if (jsonObject.data[i].user!=="") {message.user = RM.Pages.Functions.livechat_encode.decode(jsonObject.data[i].user);}else{message.user ="";}
                    RM.Pages.Functions.livechat_ListViewAddRow(message, chat_id);

                    eval('var messagebox = "rm_pages_modules_livechat_messagebox_'+chat_id+'"');
                    Ext.getCmp(messagebox).focus();
                }
            }

            setTimeout(function(){
                RM.Pages.Functions.livechat_getNewChatItems(chat_id);
            }, 2000);

        },
        failure: function() {
            Ext.Msg.alert('Status', RM.Translate.Common.UnableToShow);
        }
    };

    var conn = new Ext.data.Connection();
    conn.request(request);
    RM.Pages.Functions.livechat_admin_isTyping.status = false;

    eval('var messagebox = "rm_pages_modules_livechat_messagebox_'+chat_id+'"');
    Ext.getCmp(messagebox).focus();
};

/**
 * creates the ajax request which sends the chat message to the server.
 */
RM.Pages.Functions.livechat_sendmessage = function(messageString,chat_id){
    var request = {
        url: RM.Common.AssembleURL({
            controller : 'LiveChat',
            action: 'sendmessageJson'
        }),
        params : {
                'chat_id': chat_id,
                'message': messageString,
                'timestamp': new Date().getTime()
        },
        method: 'post',
        success: function(responseObject) {

            Ext.getCmp('rm_pages_modules_livechat_messagebox_'+chat_id).setValue("");
            Ext.getCmp('rm_pages_modules_livechat_messagebox_'+chat_id).focus();
        },
        failure: function() {
            Ext.Msg.alert('Status', RM.Translate.Common.UnableToShow);
        }
    };

    var conn = new Ext.data.Connection();
    conn.request(request);
};

/**
 * the following are basic templates for formatting the grid chat items (adds a nice bubble)
 * and also a basic table for showing the current chat information
 */
RM.Pages.Functions.livechat_columnWrap_operator = function(val){
    if (val===undefined){return;}
    if (val===""){return;}
    
    var tmpl =  '<table width="280" border="0" cellpadding="0" cellspacing="0">';
        tmpl += '<tr><td class="RM-Module-LiveChat-Left-Cell-Top"></td></tr>';
        tmpl += '<tr><td class="RM-Module-LiveChat-Left-Cell-Body x-selectable"><div class="RM-Module-LiveChat-Left-Column">'+ val +'</div></td></tr>';
        tmpl += '<tr><td class="RM-Module-LiveChat-Left-Cell-Bottom"></td></tr>';
        tmpl += '</table>';
    return tmpl;
};

RM.Pages.Functions.livechat_columnWrap_user = function(val){
    if (val===undefined){return;}
    if (val===""){return;}

    var tmpl =  '<table width="280" border="0" cellpadding="0" cellspacing="0">';
        tmpl += '<tr><td class="RM-Module-LiveChat-Right-Cell-Top"></td></tr>';
        tmpl += '<tr><td class="RM-Module-LiveChat-Right-Cell-Body x-selectable"><div class="RM-Module-LiveChat-Right-Column">'+ val +'</div></td></tr>';
        tmpl += '<tr><td class="RM-Module-LiveChat-Right-Cell-Bottom"></td></tr>';
        tmpl += '</table>';
    return tmpl;
};

RM.Pages.Functions.chatInfoTable = function(chatterInfo){
    var tmpl =  '<table width="100%" border="0" cellspacing="0" cellpadding="10"><tr>';
        tmpl += '<td bgcolor="#CCCCCC"><span class="style1">Name</span></td>';
        tmpl += '<td bgcolor="#CCCCCC"><span class="style1">Email</span></td>';
        tmpl += '<td bgcolor="#CCCCCC"><span class="style1">Question</span></td>';
        tmpl += '<td bgcolor="#CCCCCC"><span class="style1">IP Address </span></td>';
        tmpl += '</tr><tr>';
        tmpl += '<td>'+chatterInfo.name+'</td>';
        tmpl += '<td>'+chatterInfo.email+'</td>';
        tmpl += '<td>'+chatterInfo.question+'</td>';
        tmpl += '<td>'+chatterInfo.ip+'</td>';
        tmpl += '</tr></table>';
    return tmpl;
};

/**
 * sends the ajax request to accept a chat request.
 * this function does allot as it also creates the new tabs and chat dialogue gui
 */
RM.Pages.Functions.livechat_accept_chat = function(chat_id){
    
    Ext.MessageBox.confirm(RM.Translate.Admin.LiveChat.List.AcceptChat, RM.Translate.Admin.LiveChat.List.ConfirmAccept, function(buttonID){
        if (buttonID !== 'yes') {
            // reject the call
            var request = {
                url: RM.Common.AssembleURL({
                    controller : 'LiveChat',
                    action: 'closechatJson',
                    parameters : [{
                        name : 'chat_id',
                        value : chat_id
                    }]
                }),
                method: 'POST'
            };
            var conn = new Ext.data.Connection();
            conn.request(request);
            return;
        }

        // create a new store
        var store = new Ext.data.JsonStore({
            id: "rm_pages_modules_livechat_store_"+chat_id,
            fields: [
                'id','operator','user'
            ]
        });

        // rename it, because clone doesn't work for stores
        eval("RM.Pages.LiveChat_DialogueStore_"+chat_id+" = store");

        // info panel
        // Info Panel (bottom)
        var infoPanel = new Ext.Panel({
            id : 'rm_pages_livechat_chat_info_panel'+chat_id,
            region:'center',
            layout: 'form',
            height: 50,
            bodyStyle : "padding:10px",
            items : []
        });

        var DialogueGrid = new Ext.grid.GridPanel({
            id: "rm_pages_modules_livechat_dialogue_listview_"+chat_id,
            store: [
                eval("RM.Pages.LiveChat_DialogueStore_"+chat_id)
            ],
            columns: [{
                width: 0,
                dataIndex: 'id',
                hidden: true,
                hideable: false
            },{
                width: 295,
                dataIndex: 'operator',
                renderer: RM.Pages.Functions.livechat_columnWrap_operator
            },{
                width: 295,
                dataIndex: 'user',
                align: 'right',
                renderer: RM.Pages.Functions.livechat_columnWrap_user
            }],
            bodyBorder : false,
            frame : false,
            autoWidth: true,
            height: RM.Common.GetPanelHeight(300)
        });

        var inputMessageBox = new Ext.form.TextField({
            xtype: "textarea",
            id : "rm_pages_modules_livechat_messagebox_"+chat_id,
            width: 500,
            height: 50,
            cls: "RM-LiveChat-Admin-Message-Box",
            enableKeyEvents: true,
            listeners: {
                keydown: function(f, e){
                        if (e.getKey() === e.ENTER) {
                            var message = RM.Pages.Functions.livechat_encode.encode(this.getValue());
                            RM.Pages.Functions.livechat_sendmessage(message,chat_id);
                            this.focus();
                            RM.Pages.Functions.livechat_admin_isTyping.status = false;
                            RM.Pages.Functions.livechat_admin_isTyping.ChatID = "";
                        } else {
                            // set isTyping marker
                            RM.Pages.Functions.livechat_admin_isTyping.status = true;
                            RM.Pages.Functions.livechat_admin_isTyping.ChatID = chat_id;
                        }
                    }
                }

        });

        var dialoguePanel = {
            id : 'rm_pages_livechat_dialogue_'+chat_id,
            title : RM.Translate.Admin.LiveChat.Chat.ChatID+chat_id,
            closable: true,
            bodyStyle : "padding:20px",
            layout: "border",
            defaults: {
                split: true,
                useShim : true
            },
            autoScroll : true,
            containerScroll : true,
            items : [
                new Ext.Panel({
                    region:'center',
                    layout: 'form',
                    title : RM.Translate.Admin.LiveChat.Main.CurrentChat,
                    items : [
                        infoPanel,
                        DialogueGrid
                    ]
                }),
                new Ext.Panel({
                    region:'south',
                    layout: 'fit',
                    height: 50,
                    bodyStyle : "padding:10px",
                    items : [inputMessageBox]
                })
            ],
            listeners:{
                close: function(){
                    var request = {
                        url: RM.Common.AssembleURL({
                            controller : 'LiveChat',
                            action: 'closechatJson',
                            parameters : [{
                                name : 'chat_id',
                                value : chat_id
                            }]
                        }),
                        method: 'POST'
                    };
                    var conn = new Ext.data.Connection();
                    conn.request(request);
                }
            }
        };


        Ext.getCmp('rm_pages_livechat_message_tabpanel').add(dialoguePanel);
        Ext.getCmp('rm_pages_livechat_message_tabpanel').layout.setActiveItem('rm_pages_livechat_dialogue_'+chat_id);
        Ext.getCmp("rm_pages_livechat_message_tabpanel").doLayout(false,true);


        // now send the acceptance to the server...
        var request1 = {
            url: RM.Common.AssembleURL({
                controller : 'LiveChat',
                action: 'acceptchatJson',
                parameters : [{
                    name : 'chat_id',
                    value : chat_id
                },{
                    name: 'timestamp',
                    value: new Date().getTime()
                }]
            }),
            method: 'POST',
            success: function(responseObject) {

                var jsonObject = Ext.util.JSON.decode(responseObject.responseText);

                // add the chatter info to the chatter info panel
                var chatterInfo = {};
                chatterInfo.id = jsonObject.data[0].id;
                chatterInfo.name = jsonObject.data[0].user_name;
                chatterInfo.email = jsonObject.data[0].user_email;
                chatterInfo.question = jsonObject.data[0].question;
                chatterInfo.ip = jsonObject.data[0].ip;
                chatterInfo.closed = jsonObject.data[0].closed;

                Ext.getCmp('rm_pages_livechat_chat_info_panel'+chat_id).update(RM.Pages.Functions.chatInfoTable(chatterInfo));

                setTimeout(function(){
                    RM.Pages.Functions.livechat_getNewChatItems(chat_id);
                }, 4000);

            },
            failure: function() {
                Ext.MessageBox.alert(RM.Translate.Common.DeleteFailure);
            }
        };

        var conn1 = new Ext.data.Connection();
        conn1.request(request1);
    });
};



/**
 * handles the chat request list update, when this is called as long as the status
 * is set to online it will re-schedule it's self to run again
 */
RM.Pages.Functions.chatRequestList_refresh = function(){

    // reload new chat requests
    RM.Pages.LiveChat_List_Json_Store.reload();


    if (Ext.getCmp("rm_pages_modules_livechat_option_status").value==="1"){

        // check if there are new messages
        if (RM.Pages.LiveChat_List_Json_Store.data.items.length>0){
            Ext.getCmp("rm_pages_modules_livechat_sound_newchatrequest_panel").show();
            Ext.getCmp("rm_pages_modules_livechat_sound_newchatrequest_panel").hide();
        }

        // reschedule the next refresh
        RM.Pages.LiveChat_chatRequestTimer = setTimeout(function(){
            RM.Pages.Functions.chatRequestList_refresh();
        }, 4000);
    }
};

// handles the operator status, currently this version of livechat is single operator
RM.Pages.Functions.LiveChat_saveOperatorStatus = function(operatorID, operatorName, status){

    var myMask = new Ext.LoadMask('content-panel', {msg:RM.Translate.Common.PleaseWait});
    myMask.show();

    var request = {
        url: RM.Common.AssembleURL({
            controller : 'LiveChat',
            action: 'updateoperatorJson',
            parameters : [{
                name: 'online_status',
                value: status
            },{
                name : 'operator_name',
                value : operatorName
            },{
                name: "operator_id",
                value: operatorID
            }]
        }),
        method: 'POST',
        success: function(responseObject) {

            if (status==="1"){

                // set the chat request list to update...
                setTimeout(function(){
                    RM.Pages.Functions.chatRequestList_refresh();
                }, 4000);

                myMask.hide();
            } else {

                myMask.hide();
            }

        },
        failure: function() {
            myMask.hide();
            Ext.MessageBox.alert(RM.Translate.Common.DeleteFailure);
        }
    };

    var conn = new Ext.data.Connection();
    conn.request(request);
};

// gui objects
RM.Translate.Admin.LiveChat.JSON.Operators_Store = new Ext.data.JsonStore({
    url: RM.Common.AssembleURL({
        controller: 'LiveChat',
        action: 'getoperatorsJson'
    }),
    autoLoad: true,
    idProperty : 'id',
    root:'data',
    fields :[
        {name:'id', type:'string'},
        {name:'first_name', type:'string'}
    ]
});

//admin selection and online status
RM.Pages.LiveChat_Admin_Options = new Ext.Panel({
    id : 'rm_pages_livechat_admin_option_panel',
    layout: 'form',
    border: false,
    frame: false,
    height: 100,
    bodyStyle : "padding:10px",
    title : RM.Translate.Admin.LiveChat.Main.AdminOptions,
    items : [
        {
            xtype : "combo",
            fieldLabel : RM.Translate.Admin.LiveChat.Main.OperatorName,
            id : "rm_pages_modules_livechat_option_operatorname",
            hiddenName : "rm_pages_modules_livechat_option_operatorname_hidden",
            name : "rm_pages_modules_livechat_option_operatorname_name",
            store : RM.Translate.Admin.LiveChat.JSON.Operators_Store,
            forceSelection: true,
            mode: "local",
            triggerAction: 'all',
            selectOnFocus: true,
            valueField: 'id',
            displayField: 'first_name',
            allowBlank: true,
            emptyText: RM.Translate.Common.PleaseSelect,
            width : 120,
            listeners: {
                select: function(){
                    var status = Ext.getCmp("rm_pages_modules_livechat_option_status").value;
                    RM.Pages.Functions.LiveChat_saveOperatorStatus(this.value,this.lastSelectionText,status);
                }
            }
        },{
            xtype : "combo",
            fieldLabel : RM.Translate.Admin.LiveChat.Main.Status,
            id : "rm_pages_modules_livechat_option_status",
            hiddenName : "rm_pages_modules_livechat_option_status_hidden",
            name : "rm_pages_modules_livechat_option_status_name",
            store : new Ext.data.JsonStore({
                fields:[
                {
                    name:'value',
                    type:'string'
                },

                {
                    name:'text',
                    type:'string'
                }
                ],
                data: RM.Translate.Admin.LiveChat.JSON.StatusOptions
            }),
            forceSelection: false,
            mode: "local",
            triggerAction: 'all',
            selectOnFocus: true,
            valueField: 'value',
            displayField: 'text',
            allowBlank: true,
            value: 0,
            emptyText: RM.Translate.Common.PleaseSelect,
            width : 120,
            listeners: {
                select: function(){
                    var operator = Ext.getCmp("rm_pages_modules_livechat_option_operatorname");
                    RM.Pages.Functions.LiveChat_saveOperatorStatus(operator.value,operator.lastSelectionText,this.value);
                }
            }
        },{
            xtype: 'panel',
            border: false,
            html: "<div style='margin-left: 100px;padding-top: 5px;padding-bottom: 5px;'><a href='javascript:RM.Pages.Functions.Users_New();'>" + RM.Translate.Admin.LiveChat.Main.CreateOperatorMSG + "</a></div>"
        }
    ]
});

// chat list (left)
RM.Pages.LiveChat_List_Grid = new Ext.grid.GridPanel({
    id : 'rm_livechat_list_grid',
    plugins: RM.Pages.LiveChat_List_Filters,
    bbar : new Ext.PagingToolbar({
        store: RM.Pages.LiveChat_List_Json_Store,
        pageSize: 15
    }),
    enableColLock : false,
    height : 400,
    cm : RM.Pages.LiveChat_List_Columns,
    ds : RM.Pages.LiveChat_List_Json_Store,
    autoScroll: true,
    autoWidth: true
});

RM.Pages.LiveChat_List = new Ext.Panel({
    id : 'rm_pages_livechat_list',
    region:'west',
    width: 400,
    title : RM.Translate.Common.List,
    iconCls: "RM_config_livechat_icon",
    items : [
        RM.Pages.LiveChat_List_Grid,
        RM.Pages.LiveChat_Admin_Options,
        // this panel is a hidden panel just for the sound panels
        // these are just used to trigger the sound effects.
        new Ext.Panel({
            hidden: true,
            items:[
                RM.Pages.LiveChat_NotifyNewChatRequestSoundPanel,
                RM.Pages.LiveChat_NotifyNewMessageSoundPanel
            ]
        })
    ]
});

// Message Panel (right)
RM.Pages.LiveChat_Message_TabPanel = new Ext.TabPanel({
    id: "rm_pages_livechat_message_tabpanel",
    region:'center',
    title : RM.Translate.Admin.LiveChat.Main.ChatPage,
    activeTab : 0,
    frame : true,
    items : [],
    bbar: new Ext.ux.StatusBar({
        id: 'rm_livechat_chat_toolbar'
    })
});


// main gui panel
RM.Pages.LiveChat_Main_Panel = new Ext.Panel({
    id:'rm_pages_livechat_main_panel',
    layout:'border',
    defaults: {
        split: true,
        useShim : true
    },
    autoScroll : true,
    containerScroll : true,
    title: RM.Translate.Admin.LiveChat.Main.name,
    items : [
        RM.Pages.LiveChat_List,
        RM.Pages.LiveChat_Message_TabPanel
    ]
});

//
RM.Pages.Functions.LiveChat_loggedInUser = function(){

    var request = {
        url: RM.Common.AssembleURL({
            controller : 'LiveChat',
            action: 'loggedinuserJson'
        }),
        method: 'POST',
        success: function(responseObject) {
            var jsonObject = Ext.util.JSON.decode(responseObject.responseText);
            var operatorCombo = Ext.getCmp("rm_pages_modules_livechat_option_operatorname");
            operatorCombo.setValue(jsonObject.data.id);
            operatorCombo.setRawValue(jsonObject.data.first_name);
        }
    };

    var conn = new Ext.data.Connection();
    conn.request(request);
};

/**
 * this is the main function that is called to start this gui
 */
RM.Pages.Functions.LiveChat_EditJson = function () {

    // save the menu node path for later so we can update it if we need to
    RM.Pages.LiveChat_MenuNodePath = Ext.getCmp('rm_main_tree_menu').getSelectionModel().getSelectedNode().getPath();
    //Ext.Msg.alert("path",RM.Pages.LiveChat_MenuNodePath);

    Ext.getCmp('content-panel').layout.setActiveItem('rm_pages_livechat_list');
    RM.Pages.LiveChat_List_Json_Store.load({params:{start: 0, limit: 15}});
    RM.Pages.LiveChat_List_Grid.render();

    RM.Translate.Admin.LiveChat.JSON.Operators_Store.reload();
    RM.Pages.Functions.LiveChat_loggedInUser();

    //RM.Help.Load('Admin.LiveChat.List.Main');
    Ext.getCmp('content-panel').layout.setActiveItem('rm_pages_livechat_main_panel');
    Ext.getCmp("rm_pages_livechat_main_panel").doLayout(false,true);

    // set the online status
//    Ext.getCmp("rm_pages_modules_livechat_option_status").setValue(RM.Translate.Admin.LiveChat.Main.Offline);
//    Ext.getCmp("rm_pages_modules_livechat_option_status").value = 0;
    

};


RM.Main.Pages.push(RM.Pages.LiveChat_Main_Panel);